package com.jay.nio.channel.clazz.DatagramChannel;

import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class ProcessClientRequestThread implements Runnable {
	// 监听的数据报信道
	private DatagramChannel channel;

	// 连接过来的远程服务器
	private SocketAddress remoteAddress;

	// 获取信息的缓冲区
	private ByteBuffer bf;

	/**
	 * 构造函数
	 * 
	 * @param channel
	 * @param remoteAddress
	 * @param bf
	 */
	public ProcessClientRequestThread(DatagramChannel channel,
			SocketAddress remoteAddress, ByteBuffer bf) {
		this.channel = channel;
		this.remoteAddress = remoteAddress;
		this.bf = bf;

		new Thread(this).start();
	}

	@Override
	public void run() {
		try {
			System.out.println("收到了客户端的请求.");

			/********************************************
			 * 接收部分
			 ********************************************/
			// 反转此缓冲区,为下次读取做准备
			bf.flip();

			// 将字节转化为为UTF-16的字符串
			String receivedString = Charset.forName("UTF-16").newDecoder()
					.decode(bf).toString();

			// 控制台打印出来
			System.out.println("接收到来自客户端" + remoteAddress.toString() + "的信息:"
					+ receivedString);

			/********************************************
			 * 发送部分
			 ********************************************/
			// 将信息回执发送回去
			String sendString = "你好,客户端(" + remoteAddress.toString()
					+ ") 我已收到你的来信.";
			ByteBuffer bfSend = ByteBuffer.wrap(sendString.getBytes("UTF-16"));
			channel.send(bfSend, remoteAddress);

			System.out.println("处理客户端的请求完毕.");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
